# -*- encoding: utf-8 -*- 
from hashlib import sha1

from django.conf import settings
from django.db import connection
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import user_passes_test

from models import Section
from exception import ModuleNotInstalled

from django.views.decorators.cache import cache_page

# sitemap
def sitemap(request):
    sections = Section.objects.exclude(title__exact='').order_by('tree_id', 'level')

    return render_to_response('page/sitemap.html', {'sections': sections},
                              context_instance=RequestContext(request))

# Page
@cache_page(60 * 15)
def page(request):
    if request.section.app == 'home':
        page = "page/home.html"
    else:
        page = "page/index.html"

    return render_to_response(page,
                              {'section': request.section},
                              context_instance=RequestContext(request))

def get_view(app, request, *args, **kwargs):
    # Default Modulo functions
    if app == 'sitemap':
        return sitemap(request, *args, **kwargs)

    elif app == 'page' or app == 'home': 
        return page(request, *args, **kwargs)
    
    # Specific and pluggable modulo app
    elif app == 'contact':
        try:
            from modulo.contact.views import contact
            return contact(request, *args, **kwargs)
        except ImportError:
            pass

    elif app == 'groups':
        try:
            from modulo.groups.views import groups, group
            if request.object_id is not None:
                return group(request, *args, **kwargs)
            else:
                return groups(request, *args, **kwargs)
        except ImportError:
            pass

    elif app == 'gallery':
        try:
            from modulo.gallery.views import galleries, gallery
            if request.object_id is not None:
                return gallery(request, *args, **kwargs)
            else:
                return galleries(request, *args, **kwargs)
        except ImportError:
            pass

    elif app == 'map':
        try:
            from modulo.map.views import map
            return map(request, *args, **kwargs)
        except ImportError:
            pass

    elif app == 'schedule':
        try:
            from modulo.schedule.views import schedule_day
            return schedule_day(request, *args, **kwargs)
        except ImportError:
            pass

    elif app == 'sponsors':
        try:
            from modulo.sponsors.views import sponsors
            return sponsors(request, *args, **kwargs)
        except ImportError:
            pass

    elif app == 'streaming':
        try:
            from modulo.streaming.views import streaming
            return streaming(request, *args, **kwargs)
        except ImportError:
            pass
    
    raise ModuleNotInstalled(app)


def views_switcher(request, url, *args, **kwargs):
    # We compute the sha1 hash of the url
    sha1_id = sha1(url).hexdigest()

    ##
    # We are looking in the database if we have one section with this hash
    cursor = connection.cursor()
    cursor.execute("SELECT master_id FROM page_section_translation WHERE sha1 = %s", [sha1_id])
    
    row = cursor.fetchone()

    # If there is no result it doesn't exists
    if row:
        request.section = Section.objects.get(pk=row[0])

        path = request.section.get_absolute_url()
        if sha1_id != sha1(path).hexdigest():
            # If it is not the good URL for this language
            # We change to the good one
            return HttpResponseRedirect(path)
        return get_view(request.section.app, request, *args, **kwargs)
    elif request.object_id is None:
        # Try the section with associated objects
        info = url.split('/')

        if len(info) > 3:
            if info[-2].isdigit() or info[-3].isdigit():
                if info[-2].isdigit():
                    # URL du TYPE : /*/news/1/
                    id   = int(info[-2])
                    info = info[:-2]
                    info.append('')
                    url = '/'.join(info)
                else:
                    # URL du TYPE : /*/news/1/Le-succes-d-ionyse/
                    id   = int(info[-3])
                    info = info[:-3]
                    info.append('')
                    url = '/'.join(info)
                request.object_id = id
                return views_switcher(request, url, *args, **kwargs)

        # If this section doesn't exist for this language, we come back to the home page
        raise Http404

@user_passes_test(lambda u: u.is_superuser)
def changeMenuOrder(request, section_id=None):    
                
    if section_id is not None:
        menus = Section.objects.filter(parent=section_id).filter(menuLeft=True).exclude(content__exact='').order_by('orderLeft')
        i=1
        for m in menus:
            if m.orderLeft != i:
                m.orderLeft = i
                m.save()
            i=i+1
    else:
        menus = Section.objects.filter(level__exact=0).filter(menuTop=True).exclude(content__exact='').order_by('orderTop')
        i=1
        for m in menus:
            if m.orderTop != i:
                m.orderTop = i
                m.save()
            i=i+1

    if request.method == "POST":
        if request.POST['menu'] == 'top':
            if section_id is not None:
                for m in menus:
                    if m.orderLeft != request.POST[str(m.orderLeft)]:
                        m.orderLeft = request.POST[str(m.orderLeft)]
                        m.save()
            else:
                for m in menus:
                    if m.orderTop != request.POST[str(m.orderTop)]:
                        m.orderTop = request.POST[str(m.orderTop)]
                        m.save()
            return HttpResponseRedirect(request.path)
  
    return render_to_response('admin/changeMenuOrder.html', {'menus': menus, 'section': section_id},
                              context_instance=RequestContext(request))
